/*
 * @Date: 2023-08-08 09:24:49
 * @LastEditors: lyx
 * @LastEditTime: 2023-11-15 19:38:57
 * @FilePath: \sup-mini-app\src\utils\api.ts
 * @Description:
 */
import axios from "axios";
import { TaroAdapter } from "axios-taro-adapter";
import Taro from "@tarojs/taro";
const API_URL = "http://localhost:3000";
const showErrorToast = (msg) => {
  Taro.showToast({
    title: msg,
    icon: "none",
  });
};

// 处理  类型“AxiosResponse<any, any>”上不存在属性“errorinfo”。ts(2339) 脑壳疼！关键一步。
// Axios响应模式如下所示：
// {
//   data: {},
//   status: 200,
//   statusText: 'OK',
//   headers: {},
//   config: {},
//   request: {}
// }
declare module "axios" {
  interface AxiosResponse<T = any> {
    content: any;
    msg: any;
    code: any;
    url?: string;
  }
  export function create(config?: AxiosRequestConfig): AxiosInstance;
}

const SupRequest = axios.create({
  baseURL: API_URL,
  timeout: 10000,
  adapter: TaroAdapter, // add this line，添加这一行使用taroAdapter
});

// request拦截器
SupRequest.interceptors.request.use(
  (config) => {
    Taro.showLoading({
      title: "加载中",
      mask: true,
    });
    let tokenId = Taro.getStorageSync("tokenId");
    if (typeof tokenId == "undefined") {
      tokenId = "";
    }
    config.headers = {
      "Content-Type": "application/json;charset=utf-8",
      Authorization: tokenId,
    };
    return config;
  },
  (error) => {
    // Do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// respone拦截器
SupRequest.interceptors.response.use(
  (response) => {
    Taro.hideLoading();
    if (response.data.isError) {
      showErrorToast(response.data.error.message);
      if (response.data.error.codeNumber === "A0230") {
        // 登录失效
        Taro.navigateTo({
          url: "/pages/login/index",
        });
      }
    } else {
      return response.data;
    }
  },
  (error) => {
    Taro.hideLoading();
    console.log("error", error); // for debug
    showErrorToast(error.message);
    return Promise.reject(error);
  }
);

export default SupRequest;
